<template>
  <div class="box">
    <!-- 
      on-preview	点击文件列表中已上传的文件时的钩子	
      on-remove	文件列表移除文件时的钩子 
      on-exceed	文件超出个数限制时的钩子
      file-list	上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]
      before-upload	上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
      on-success	文件上传成功时的钩子	
    -->
    <div class="select_box">
      <div class="title">请选择书柜:</div>
      <el-select
        v-model="value"
        size="small"
        placeholder="请选择"
        class="select"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>
    <el-upload
      class="upload-demo"
      :action="addExcelUrl"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-change="handleChange"
      :multiple="false"
      :show-file-list="true"
      :auto-upload="false"
      :file-list="fileList"
      :limit="1"
      :on-exceed="handleExceed"
      accept=".xlsx, .xls"
    >
      <!-- :disabled="!value" -->
      <!-- v-if="value" -->
      <el-button slot="trigger" size="small" type="primary">
        + 点击导入Excel</el-button
      >
      <!-- <el-tooltip
        class="item"
        v-else
        effect="dark"
        content="请先选择书柜列表后再点击上传"
        placement="top"
      >
        <el-button size="small" type="primary" disabled>
          + 点击选择Excel文件</el-button
        >
      </el-tooltip> -->

      <div slot="tip" class="el-upload__tip">
        <p class="p1">注意：只能上传.xlsx文件</p>
        <p v-for="(item, index) in tipsData" :key="index">{{ item }}</p>
      </div>
    </el-upload>

    <div class="record_number">
      <a href="https://beian.miit.gov.cn" target="_blank"
        >备案号(京ICP备2021000259号)</a
      >
    </div>
  </div>
</template>
<script>
import { index, addExcel } from "@/api";
import * as XLSX from "xlsx";
export default {
  components: {},
  data() {
    return {
      addExcelUrl: "https://book.farmhelper.top/bookcase/book_excel_add",
      fileList: [],
      tooltipContent: "请先选择书柜",
      options: [],
      value: "",
      auth: "",
      tipsData: [],
      excelFile: "",
      loading: "",
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  watch: {},
  created() {},
  mounted() {
    const { auth } = this.$route.query;
    this.auth = auth;
    this.getSelectIndex();
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      window.open(file.url);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },

    handleChange(file, fileList) {
      this.excelFile = file.raw; // 获取原始文件对象
      // this.loading = this.$loading({
      //   lock: true,
      //   text: "解析中",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: "array" });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 2 });
        console.log(jsonData);

        // jsonData.forEach((item,index) => {
        //   if (index > 15) {
        //     console.log(item.name, JSON.parse(item.context));
        //   }
        //   item.context = JSON.parse(item.context)
        // });

        // if (jsonData.length > 200) {
        //   resultDataOld = jsonData.slice(0, 200);
        // } else {
        //   resultDataOld = jsonData;
        // }

        let resultDataOld = [];
        jsonData.forEach((item, index) => {
          resultDataOld.push(item.ISBN || item.isbn);
        });
        let resultData = [];
        if (resultDataOld.length > 200) {
          this.$message.error("最大上传200条数据");
          resultData = resultDataOld.slice(0, 200);
        } else {
          resultData = resultDataOld;
        }
        console.log("resultDataOld", resultData);
        this.postAddExcel(resultData);
      };
      reader.readAsArrayBuffer(file.raw);
    },
    beforeUpload(file) {
      if (!this.value) {
        this.$message.error("请选择书柜");
        return;
      }
      const isExcel = /\.(xlsx|xls|XLSX|XLS)$/.test(file.name);
      if (!isExcel) {
        this.$message.error("只能上传.xlsx、.xls格式的文件!");
        return false;
      }
    },
    // submitUpload(){
    //   this.postAddExcel(formData)
    // },
    getSelectIndex() {
      let params = {
        auth: this.auth,
      };
      index({ params })
        .then((res) => {
          const { code, msg, result } = res;
          if (code == 1) {
            result.bookcase.forEach((item) => {
              this.options.push({ label: item.name, value: item.id });
            });
            this.tipsData = result.hint;
          }
        })
        .catch((error) => {});
    },
    postAddExcel(excel) {
      let parames = {
        excel,
        bookcase_id: this.value,
        auth: this.auth,
      };
      addExcel(parames)
        .then((res) => {
          const { code, msg } = res;
          this.$message({
            showClose: true,
            message: msg,
            type: code == 1 ? "success" : "error",
          });
          this.loading.close();
        })
        .catch((error) => {
          // this.$message({
          //   showClose: true,
          //   message: "接口出错",
          //   type: "error",
          // });
        });
    },
  },
  destroyed() {},
};
</script>

<style lang="scss" scoped>
.box {
  padding: 80px 150px;
}
.select_box {
  display: flex;
  align-items: center;
  margin: 0px 50px 50px 0px;

  .title {
    font-size: 16px;
    color: #000000;
    font-weight: bold;
    margin-right: 10px;
  }
}
.record_number {
  position: absolute;
  z-index: 1;
  bottom: 10px;
  left: 50%;
  font-size: 14px;
  color: #606266;
  transform: translateX(-50%);
}

.upload-demo {
  .el-button {
    font-size: 18px;
    color: #fff;
    font-weight: bold;
  }
  .el-upload__tip {
    line-height: 1.8;
    .p1 {
      margin-bottom: 10px;
    }
  }
}
</style>
